package util

import (
	"encoding/base64"
	"io/ioutil"
	"os"
	"path/filepath"
	"strings"
)

type Img struct {
	Path          string
	Base64Strings string
}

func GetAllImageBase64(rootDir string) ([]Img, error) {
	var imgs []Img
	err := filepath.Walk(rootDir, func(path string, info os.FileInfo, err error) error {
		if err != nil {
			return err
		}
		if !info.IsDir() && isImageFile(path) {
			base64Str, err := imageFileToBase64(path)
			if err != nil {
				return err
			}
			imgs = append(imgs, Img{
				Path:          path,
				Base64Strings: base64Str,
			})
		}
		return nil
	})
	return imgs, err
}

func isImageFile(path string) bool {
	ext := strings.ToLower(filepath.Ext(path))
	return ext == ".jpg" || ext == ".jpeg" || ext == ".png" || ext == ".gif"
}

func imageFileToBase64(filePath string) (string, error) {
	img, err := ioutil.ReadFile(filePath)
	if err != nil {
		return "", err
	}
	return base64.StdEncoding.EncodeToString(img), nil
}
